package st.learnopengl.apps.advance

import glm_.glm
import glm_.mat4x4.Mat4
import glm_.vec3.Vec3
import glm_.vec4.Vec4
import gln.glClearColor
import gln.uniform.glUniform
import st.learnopengl.common.App
import org.lwjgl.opengl.GL11C.*
import st.learnopengl.apps.assets.Model
import st.learnopengl.apps.assets.ModelLoader
import st.learnopengl.apps.assets.Program

class FullBoneAnimation(width: Int, height: Int, title: String) : App(width, height, title) {

    private lateinit var model: Model

    private var camera: Mat4 = glm.lookAt(Vec3(0, 20, 10), Vec3(0, 5, 0), Vec3(0, 1, 0))
    private var modelMatrix: Mat4 = Mat4()
    private var projection: Mat4 = glm.perspective(glm.radians(60.0f), 4.0f / 3.0f, 0.0001f, 1000.0f)

    private var mvpLocation: Int = -1
    private var gBonesLocation: Int = -1

    private var mStartTime: Long = -1

    private var program: Program =
        Program("shaders/boneanim/full_vs.glsl", "shaders/boneanim/full_fs.glsl")
    override fun onInit() {
        model = ModelLoader().load("untitled2.dae")

        model.build()

        program.build()


        mvpLocation = program.program!!.getUniformLocation("mvp")
        gBonesLocation = program.program!!.getUniformLocation("gBones")

        modelMatrix = modelMatrix.rotate(-90.0f, Vec3(1, 0, 0))

        glClearColor(Vec4(0.3, 0.4, 0.5, 1.0))
        glEnable(GL_DEPTH_TEST)
    }

    private fun getRunningTime(): Float {
        if (mStartTime < 0) mStartTime = System.currentTimeMillis()


        val deltaTime =  (System.currentTimeMillis() - mStartTime).toFloat() / 1000.0f

        if (deltaTime > 0.8f) {
            mStartTime = System.currentTimeMillis()
            return 0.0f
        } else {
            return deltaTime
        }
    }

    override fun loop() {
        glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT)

        program.program!!.use {
            glUniform(mvpLocation, projection * camera * modelMatrix)



            model.render(program, getRunningTime())
        }

    }


    companion object {

        @JvmStatic
        fun main(args: Array<String>) {
            FullBoneAnimation(1280, 720, "Full Bone Animation").run()
        }
    }
}